package com.mujin.keji.collectionsystem.server;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;

import com.mujin.keji.collectionsystem.Constant;
import com.mujin.keji.collectionsystem.R;
import com.mujin.keji.collectionsystem.module.main.views.MainActivity;
import com.mujin.keji.collectionsystem.utils.DateUtil;
import com.mujin.keji.collectionsystem.utils.EmptyUtils;
import com.mujin.keji.collectionsystem.utils.FileUtil;
import com.mujin.keji.collectionsystem.utils.RecorderUtil;
import com.mujin.keji.collectionsystem.utils.RxTimerUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class RecordServcie extends Service {
    private static final String TAG = "MyService";

    @Override
    public IBinder onBind(Intent intent) {
        Log.e(TAG, "onBind: ...");

        return new MyBinder();
    }

    @Override
    public boolean onUnbind(Intent intent) {
        return super.onUnbind(intent);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: ...");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e(TAG, "onStartCommand: ...");


// 在API11之后构建Notification的方式
        Notification.Builder builder = new Notification.Builder
                (this.getApplicationContext()); //获取一个Notification构造器
        Intent nfIntent = new Intent(this, MainActivity.class);

        builder.setContentIntent(PendingIntent.getActivity(this, 0, nfIntent, 0)) // 设置PendingIntent
                .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),
                        R.drawable.image_about_logo)) // 设置下拉列表中的图标(大图标)
                .setContentTitle("录音服务") // 设置下拉列表里的标题
                .setSmallIcon(R.mipmap.ic_launcher) // 设置状态栏内的小图标
                .setContentText("录音服务") // 设置上下文内容
                .setWhen(System.currentTimeMillis()); // 设置该通知发生的时间

        Notification notification = builder.build(); // 获取构建好的Notification
        notification.defaults = Notification.DEFAULT_SOUND; //设置为默认的声音
        // 参数一：唯一的通知标识；参数二：通知消息。
        startForeground(110, notification);// 开始前台服务

        return super.onStartCommand(intent, flags, startId);


    }

    private RecorderUtil recorder;

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: ...");
        super.onDestroy();
        if(EmptyUtils.isNotEmpty(recorder)){
            recorder.stopRecording();
        }

        EventBus.getDefault().post("stopRecord");
        RxTimerUtil.cancel();
        stopForeground(true);// 停止前台服务--参数：表示是否移除之前的通知

    }

    private String recordDir = "aarecordings";


    public class MyBinder extends Binder {
        public void startRecording(RecorderUtil recorderUtil, Long visitId) {
            recorder = recorderUtil;
            Constant.visitId = visitId;
            recorder.startRecording();
            EventBus.getDefault().post("startRecord");
            //开启定时器
            RxTimerUtil.interval(20000, new RxTimerUtil.IRxNext() {
                @Override
                public void doNext() {
                    String path = recorder
                            .getFilePath();
                    File file = new File(path);
                    try {
                        long size = FileUtil.getFileSizes(file);
                        Log.e(TAG, "doNext: " + size);
                        if (size >= 1024 * 1024 * 8) {
                            Log.e(TAG, "doNext: 重新录音");
                            //停止
                            recorder.stopRecording();
                            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
                            String recordFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + recordDir + "/" + timeStamp + ".mp3";
                            String jsonFileName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + recordDir + "/" + timeStamp + ".txt";
                            recorder.setJsonFileName(jsonFileName);
                            recorder.setRecordFileName(recordFileName);
                            recorder.setTimeStamp(timeStamp);
                            //
                            recorder.getVisitUserDto().setTime(DateUtil.coverDateFormat("yyyyMMddHHmmss", new Date()));
                            recorder.getVisitUserDto().setFileTime(DateUtil.coverDateFormat(DateUtil.DEFAULT_DATE_FORMATTER, new Date()));
                            recorder.getVisitUserDto().setFileName(timeStamp);
                            recorder.getVisitUserDto().setFilePath(recordFileName);
                            recorder.getVisitUserDto().setTxtFilePath(jsonFileName);
                            //开始
                            recorder.startRecording();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }

}

